<template>
  <ContentWrap>
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/course/list' }">课程列表</el-breadcrumb-item>
        <el-breadcrumb-item>信息编辑</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 基本信息 -->
    <div class="basic-info">
      <div class="info-header">
        <div class="info-title">基本信息</div>
      </div>
      <div class="info-content">
        <div class="info-item">
          <span class="item-label">课程编号：</span>
          <span class="item-value">{{ courseInfo.courseCode || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="item-label">所属分类：</span>
          <span class="item-value">{{ courseInfo.categoryPathName || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="item-label">课程主题：</span>
          <span class="item-value">{{ courseInfo.title }}</span>
        </div>
        <div class="info-item">
          <span class="item-label">课程概述：</span>
          <span class="item-value">{{ courseInfo.courseIntroduction || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="item-label">主讲人：</span>
          <span class="item-value">{{ courseInfo.speaker || '-' }}</span>
        </div>
      </div>
    </div>

    <!-- 选项卡 -->
    <div class="tabs-container">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="课程介绍" name="intro">
          <div class="tab-content">
            <div class="upload-section">
              <div class="section-title">
                <span class="required">*</span>
                <span>专题宣传图：</span>
              </div>
              <div class="upload-container">
                <div class="upload-item">
                  <UploadImgs
                    v-model="bannerList"
                    :limit="10"
                    :is-show-tip="true"
                    @upload-success="handleBannerUploadSuccess"
                  />
                </div>
              </div>
            </div>

            <div class="upload-section">
              <div class="section-title">
                <span class="required">*</span>
                <span>详情介绍：</span>
              </div>
              <div class="upload-container">
                <div class="upload-item">
                  <UploadImgs
                    v-model="descPicList"
                    :limit="10"
                    :is-show-tip="true"
                    @upload-success="handleDescPicUploadSuccess"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="课程内容" name="content">
          <div class="tab-content">
            <div class="content-header">
              <el-button type="primary" @click="openLessonForm">添加内容</el-button>
            </div>
            <el-table
              :data="lessonList"
              border
              style="width: 100%"
              :header-cell-style="{background:'#f8f8f9'}"
            >
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="courseName" label="课节名称" min-width="150" />
              <el-table-column prop="courseType" label="课程类型" width="100" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.courseType === '1'" type="success">视频课</el-tag>
                  <el-tag v-else-if="scope.row.courseType === '2'" type="info">图文课</el-tag>
                  <el-tag v-else type="warning">其他</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="isFree" label="是否免费" width="100" align="center">
                <template #default="scope">
                  <el-tag v-if="!scope.row.isFree" type="danger">付费</el-tag>
                  <el-tag v-else type="success">免费</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="sortOrder" label="排序" width="100" align="center" />
              <el-table-column prop="createUser" label="创建人" width="100" align="center" />
              <el-table-column prop="createTime" label="创建时间" width="150" align="center">
                <template #default="scope">
                  {{ formatTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                  <el-button link type="primary" @click="editLesson(scope.row)">编辑</el-button>
                  <el-button link type="danger" @click="deleteLesson(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <Pagination
              v-if="lessonTotal > 0"
              :total="lessonTotal"
              v-model:page="lessonQueryParams.pageNo"
              v-model:limit="lessonQueryParams.pageSize"
              @pagination="getLessonList"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 底部按钮 -->
    <div v-if="activeTab === 'intro'" class="footer-actions">
      <el-button type="primary" @click="saveEdit">保存编辑</el-button>
    </div>

    <!-- 添加内容模态框 -->
    <el-dialog
      v-model="lessonFormVisible"
      :title="lessonFormTitle"
      width="600px"
      destroy-on-close
    >
      <el-form :model="lessonForm" label-width="80px">
        <el-form-item label="课节名称" required>
          <el-input v-model="lessonForm.courseName" placeholder="请输入课节名称" />
        </el-form-item>
        <el-form-item label="是否免费">
          <el-switch v-model="lessonForm.isFree" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="lessonForm.sortOrder" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="课程类型" required>
          <el-radio-group v-model="lessonForm.courseType">
            <el-radio label="1">视频课</el-radio>
            <el-radio label="2">图文课</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" required>
          <div class="video-upload-container">
            <!-- 已上传视频预览 -->
            <div v-if="videoUrl && !isUploading" class="video-preview-container">
              <div class="video-header">
                <span class="video-title">视频预览</span>
                <div class="video-actions">
                  <el-button type="primary" size="small" @click="handleReupload">
                    <Icon icon="ep:upload-filled" />
                    重新上传
                  </el-button>
                </div>
              </div>
              <video :src="videoUrl" controls class="video-player"></video>
            </div>

            <!-- 上传组件 -->
            <el-upload
              v-if="!videoUrl || isUploading"
              ref="uploadRef"
              :action="getUploadUrl()"
              :limit="1"
              :before-upload="beforeVideoUpload"
              :http-request="customUploadRequest"
              :show-file-list="false"
              accept=".mp4,.avi,.mov,.wmv,.flv,.mkv"
              class="video-uploader"
              @on-exceed="handleExceed"
              @on-remove="handleRemove"
              @on-success="handleUploadSuccess"
            >
              <el-button type="primary">
                <Icon icon="ep:upload-filled" />
                选取视频
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传视频格式：mp4, avi, mov, wmv, flv, mkv，大小不超过500MB
                </div>
              </template>
            </el-upload>

            <!-- 上传进度条 -->
            <div v-if="isUploading" class="upload-progress">
              <el-progress :percentage="uploadProgress" :format="percentageFormat" />
              <div class="progress-text">
                <span v-if="uploadProgress < 100">正在上传视频，请耐心等待...</span>
                <span v-else>文件已上传，正在处理中...</span>
              </div>
            </div>
          </div>
<!--          <div class="el-upload__tip">-->
<!--            支持上传视频格式：mp4, avi, mov, wmv, flv, mkv，大小不超过500MB-->
<!--          </div>-->
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="lessonFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveLessonForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadImgs, UploadFile } from '@/components/UploadFile'
import * as CourseApi from '@/api/course/info'
import { getUploadUrl, useUpload, type ProgressCallback } from '@/components/UploadFile/src/useUpload'
import { CourseInfoVO, CourseDetailVO } from '@/api/course/info'
import type { UploadRequestOptions } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'CourseDetail' })

// 获取路由参数
const route = useRoute()
const courseId = computed(() => Number(route.params.id))

// 选项卡
const activeTab = ref('intro')

// 课程信息
const courseInfo = ref<CourseInfoVO>({
  id: 0,
  courseCode: '',
  categoryId: undefined,
  categoryPath: '',
  categoryPathName: '',
  title: '',
  courseIntroduction: '',
  speaker: '',
  picUrl: '',
  banner: '',
  courseDescPic: ''
})

// 专题宣传图列表
const bannerList = ref<string[]>([])

// 详情介绍图片列表
const descPicList = ref<string[]>([])

// 视频URL
const videoUrl = ref<string>('')
const uploadRef = ref()
const uploadProgress = ref(0)
const isUploading = ref(false)

// 格式化进度条百分比
const percentageFormat = (percentage: number) => {
  return percentage === 100 ? '上传完成' : `${percentage}%`
}

// 格式化时间显示
const formatTime = (timestamp: number | string) => {
  if (!timestamp) return ''
  return formatDate(new Date(Number(timestamp)), 'YYYY-MM-DD HH:mm:ss')
}

// 上传前检查
const beforeVideoUpload = (file: any) => {
  // 检查文件类型
  const validTypes = ['video/mp4', 'video/avi', 'video/quicktime', 'video/x-msvideo', 'video/x-ms-wmv', 'video/x-flv', 'video/x-matroska']
  const isValidType = validTypes.includes(file.type)
  if (!isValidType) {
    ElMessage.error('请上传正确的视频格式！')
    return false
  }

  // 检查文件大小
  const isLt500M = file.size / 1024 / 1024 < 500
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过 500MB!')
    return false
  }

  // 重置进度
  uploadProgress.value = 0
  return true
}

// 自定义上传请求
const customUploadRequest = (options: UploadRequestOptions) => {
  const { file, onSuccess, onError } = options

  // 设置为正在上传状态
  isUploading.value = true
  uploadProgress.value = 0

  // 创建FormData
  const formData = new FormData()
  formData.append('file', file)

  // 使用公共上传组件的useUpload，传入进度回调函数
  const updateProgress: ProgressCallback = (percentage) => {
    uploadProgress.value = percentage

    // 如果进度到达100%，1秒后关闭上传状态，显示视频预览
    if (percentage === 100) {
      setTimeout(() => {
        isUploading.value = false
      }, 1000)
    }
  }

  // 使用axios上传
  const { httpRequest } = useUpload(updateProgress)

  // 调用公共上传方法
  return httpRequest(options).then(response => {
    // 保存视频URL
    if (response.data) {
      videoUrl.value = response.data
      lessonForm.value.classInfoUrl = response.data
    }

    // 显示成功消息
    ElMessage.success('上传成功')

    // 如果有成功回调，调用它
    if (onSuccess) {
      onSuccess(response)
    }

    return response
  }).catch(error => {
    console.error('上传失败', error)
    ElMessage.error('上传失败，请重试')
    isUploading.value = false
    uploadProgress.value = 0

    // 如果有错误回调，调用它
    if (onError) {
      onError(error)
    }

    throw error
  })
}

// 处理上传成功
const handleUploadSuccess = (response: any) => {
  // 设置视频URL以便预览
  if (response && response.data) {
    videoUrl.value = response.data
    lessonForm.value.classInfoUrl = response.data
  }

  // 显示成功消息
  ElMessage.success('上传成功')
  uploadProgress.value = 100
}

// 处理文件数量超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个视频文件')
}

// 处理移除文件
const handleRemove = () => {
  videoUrl.value = ''
  lessonForm.value.classInfoUrl = ''
  uploadProgress.value = 0
  isUploading.value = false
}

// 重新上传视频
const handleReupload = () => {
  videoUrl.value = ''
  lessonForm.value.classInfoUrl = ''
  uploadProgress.value = 0
  isUploading.value = false

  // 清空上传文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 课程内容列表
const lessonList = ref<CourseDetailVO[]>([])

// 课程内容分页参数
const lessonQueryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

// 课程内容总数
const lessonTotal = ref(0)

// 添加内容弹窗相关
const lessonFormVisible = ref(false)
const lessonFormTitle = ref('添加内容')
const lessonForm = ref<CourseDetailVO>({
  id: undefined,
  courseId: courseId.value,
  courseName: '',
  isFree: true,
  courseType: '1',
  sortOrder: 0,
  classInfoUrl: '',
  createUser: ''
})

// 打开添加内容弹窗
const openLessonForm = () => {
  lessonFormVisible.value = true
  lessonFormTitle.value = '添加内容'

  // 重置表单
  lessonForm.value = {
    id: undefined,
    courseId: courseId.value,
    courseName: '',
    isFree: true,
    courseType: '1',
    sortOrder: 0,
    classInfoUrl: '',
    createUser: ''
  }

  // 重置视频URL和上传进度
  videoUrl.value = ''
  uploadProgress.value = 0

  // 清空上传文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 编辑课程内容
const editLesson = (lesson: CourseDetailVO) => {
  lessonFormVisible.value = true
  lessonFormTitle.value = '编辑内容'

  // 填充表单数据
  lessonForm.value = {
    ...lesson,
    classInfoUrl: lesson.classInfoUrl || ''
  }
  videoUrl.value = lesson.classInfoUrl || ''
  uploadProgress.value = 0

  // 清空上传文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 删除课程内容
const deleteLesson = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程内容吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用API删除课程内容
    await CourseApi.deleteCourseDetail(id)
    ElMessage.success('删除成功')

    // 重新加载列表
    getLessonList()
  } catch (error) {
    console.error('删除课程内容失败', error)
    ElMessage.error('删除失败')
  }
}

// 获取课程内容列表
const getLessonList = async () => {
  try {
    const res = await CourseApi.getCourseDetailPage(courseId.value, lessonQueryParams)
    lessonList.value = res.list
    lessonTotal.value = res.total
  } catch (error) {
    console.error('获取课程内容列表失败', error)
    ElMessage.error('获取课程内容列表失败')
  }
}





// 保存课程内容
const saveLessonForm = async () => {
  try {
    // 表单验证
    if (!lessonForm.value.courseName) {
      ElMessage.warning('请输入课节名称')
      return
    }
    if (!videoUrl.value) {
      ElMessage.warning('请上传视频内容')
      return
    }

    // 将视频URL设置到表单中
    lessonForm.value.classInfoUrl = videoUrl.value

    // 设置课程ID
    lessonForm.value.courseId = courseId.value

    // 设置创建人为当前登录用户的昵称
    if (!lessonForm.value.id) { // 只在新增时设置创建人
      const userStore = useUserStore()
      lessonForm.value.createUser = userStore.getUser.nickname
    }

    if (lessonForm.value.id) {
      // 更新课程内容
      await CourseApi.updateCourseDetail(lessonForm.value)
    } else {
      // 创建课程内容
      await CourseApi.createCourseDetail(lessonForm.value)
    }

    // 关闭弹窗
    lessonFormVisible.value = false
    ElMessage.success('保存成功')

    // 重新加载列表
    getLessonList()
  } catch (error) {
    console.error('保存课程内容失败', error)
    ElMessage.error('保存失败')
  }
}

// 获取课程详情
const getCourseDetail = async () => {
  try {
    const res = await CourseApi.getCourseInfo(courseId.value)
    courseInfo.value = res

    // 处理专题宣传图
    if (courseInfo.value.banner) {
      bannerList.value = courseInfo.value.banner.split(',')
    }

    // 处理详情介绍图片
    if (courseInfo.value.courseDescPic) {
      descPicList.value = courseInfo.value.courseDescPic.split(',')
    }
  } catch (error) {
    console.error('获取课程详情失败', error)
    ElMessage.error('获取课程详情失败')
  }
}

// 处理专题宣传图上传成功
const handleBannerUploadSuccess = () => {
  // 更新课程信息中的banner字段
  courseInfo.value.banner = bannerList.value.join(',')
}

// 处理详情介绍图片上传成功
const handleDescPicUploadSuccess = () => {
  // 更新课程信息中的courseDescPic字段
  courseInfo.value.courseDescPic = descPicList.value.join(',')
}

// 保存编辑
const saveEdit = async () => {
  try {
    // 确保专题宣传图和详情介绍图片已更新到courseInfo中
    courseInfo.value.banner = bannerList.value.join(',')
    courseInfo.value.courseDescPic = descPicList.value.join(',')

    // 调用API保存课程详情
    await CourseApi.updateCourseInfo(courseInfo.value)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存课程详情失败', error)
    ElMessage.error('保存失败')
  }
}

// 初始化
onMounted(() => {
  getCourseDetail()

  // 如果选中的是课程内容标签页，加载课程内容列表
  if (activeTab.value === 'content') {
    getLessonList()
  }
})

// 监听标签页切换
watch(() => activeTab.value, (newVal) => {
  if (newVal === 'content') {
    getLessonList()
  }
})
</script>

<style scoped>
.breadcrumb-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px 20px;
  margin-bottom: 15px;
}

.video-preview-container {
  margin-top: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.video-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.video-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.video-actions {
  display: flex;
  gap: 10px;
}

.video-player {
  width: 100%;
  max-height: 300px;
}

.video-preview {
  max-width: 160px;
  max-height: 90px;
  margin-right: 10px;
}

.video-file-name {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.el-upload-list__item-thumbnail {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.upload-progress {
  margin-top: 10px;
}

.progress-text {
  margin-top: 5px;
  color: #606266;
  font-size: 14px;
}

.basic-info {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.info-title {
  font-size: 16px;
  font-weight: bold;
}

.info-content {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
}

.item-label {
  color: #606266;
  margin-right: 5px;
}

.item-value {
  color: #303133;
}

.tabs-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.tab-content {
  padding: 20px 0;

  .content-header {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
  }
}



.upload-section {
  margin-bottom: 30px;
}

.section-title {
  margin-bottom: 15px;
}

.required {
  color: #f56c6c;
  margin-right: 5px;
}

.upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.upload-item {
  text-align: center;
}

.upload-text {
  margin-top: 5px;
  color: #606266;
}

.video-upload-box {
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.video-upload-box:hover {
  border-color: #409eff;
}

.footer-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 添加内容模态框样式 */
:deep(.el-dialog__body) {
  padding-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.video-upload {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.video-upload:hover {
  border-color: #409eff;
}

.video-upload-box {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-text {
  margin-top: 10px;
  color: #606266;
}

.video-upload-container {
  width: 100%;
}

.video-uploader {
  width: 100%;
}

.upload-progress {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.progress-text {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}
</style>
